
local jass = require 'jass.common'
local japi = require 'jass.japi'
local code = require 'jass.code'
local http = require 'http.http'
local sync = require 'http.sync'

http.json = require 'http.json'
http.base64 = require 'http.base64'
http.map = '独断万古'
http.url = '43.136.104.7:10000'

print(os.clock(),'初始化')

--开始时间
http.start_time = os.clock()

--初始化玩家数据
http.init(function(result)
    http.load_time = os.clock()
    print(http.load_time - http.start_time,'拉取玩家数据耗时')
    sync.send_sync('玩家存档',result)
end)

--同步完成处理
function sync.finish_sync(class,result)
    if class=='玩家存档' then
        http.init_data(result)
    elseif class=='热补丁' and http.sync_hotfix then
        http.sync_hotfix(result)
    end
end

--初始化玩家数据结束 
http['init_end'] = function(flag,err)
    if flag then
        --==调用数据读取
        if code['SyncTriggerAction'] then
            code['SyncTriggerAction']()
        end
    else
        print(flag)
    end
end


code['HTTPMap'] = function(mapid)
    http['map'] = mapid
end

code['HTTPUrl'] = function(url)
    http['url'] = url
end

--初始化
code['HTTPInit'] = function(url)
    http.init(function(result)
        http.load_time = os.clock()
        print(http.load_time - http.start_time,'拉取玩家数据耗时')
        sync.send_sync('玩家存档',result)
    end)
    
    http.init_rank()
end

--同步是否结束
code['HTTPSyncend'] = function()
    return http.init_end
end


local info = {
    ['HTTPGet'] = http.get,
    ['HTTPSet'] = http.set,
    ['HTTPupload'] = http.upload,
    ['HTTPConfig'] = http.get_config,
}

for k,func in pairs(info) do
    code[k] = function(...)
        local num = func(...)
        return tostring(num)
    end
end

local rank = {
    ['HTTPRank_name'] = 1,
    ['HTTPRank_grade'] = 2,
    --['HTTPRank_kkid'] = 2,
}
for k,id in pairs(rank) do
    code[k] = function(key,index)
        local data1 = http.get_rank(key)
        local data2 = data1[index]
        if data2 then
            return data2[id]
        end
        return "" 
    end
end


--初始化排名
--http.init_rank(function()
--    print(os.clock(),'排名获取',http['ranks_data'])
--    local data1 = http.get_rank('排行榜1')
--    for k,v in ipairs(data1) do
--        print(k,table.concat(v,'\t'))
--    end
--end)




----同步失败下面函数使用无效
----读取玩家服务器数据
----返回 整数或者字符串
--http.get(player,key)
--
----设置玩家数据(缓存没上传)
--http.set(player,key,num)
--
----提交玩家数据
--http.upload(player)
--
----获取全局存档
----返回 字符串
--http.get_config(key)
--
----获取排行榜
----返回 表
--
--http.get_rank(key)
